package ldh.im.web.controller;

import com.google.code.kaptcha.Producer;
import ldh.im.web.constant.LogType;
import ldh.im.web.interceptor.ErrorHandler;
import ldh.im.web.service.LogService;
import ldh.im.web.service.UserService;
import ldh.im.web.util.UserUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.SavedRequest;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.OutputStream;

@Controller
public class LoginController {

    private static final Logger LOGGER = LoggerFactory.getLogger(LoginController.class);

    @Resource
    private Producer producer;
    @Resource
    private UserService userService;
    @Resource
    private LogService logService;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String loginUser(String userName, String password, String validateCode, HttpSession session, HttpServletRequest request) {
        String imageCode = (String) session.getAttribute("imageCode");
        if (!validateCode.equals(imageCode)) {
            session.setAttribute("error", "验证码错误");
            return "redirect:login";
        }
        UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(userName,password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(usernamePasswordToken);   //完成登录
            Object user = subject.getPrincipal();
            session.setAttribute("user", user);
            logService.insert(userService.getByKey(UserUtil.getLoginUser()), null, LogType.login, "用户登录管理后台");

            SavedRequest reqUrl = WebUtils.getSavedRequest(request);
            if (reqUrl != null) {
                String URL= reqUrl.getRequestUrl();
                return "redirect:" + URL;
            }
            return "redirect:main";
        } catch(Exception e) {
            LOGGER.error("login error", e);
            //返回登录页面
        }
        return "redirect:login";
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(HttpSession session) {
        return "login";
    }

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String toLogin(HttpSession session) {
        return "login";
    }


    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logOut(HttpSession session) {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            subject.logout();
        }
        return "login";
    }

    @RequestMapping(method = RequestMethod.GET, value = "/caprica")
    public void capricaImage(HttpServletResponse response, HttpSession session) throws Exception {
        String code = producer.createText();
        session.setAttribute("imageCode", code);

        BufferedImage image = producer.createImage(code);
        response.setContentType("image/jpg");
        OutputStream os = response.getOutputStream();
        ImageIO.write(image, "jpg", os);
    }
}
